package com.example.orderminiappapi.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.http.HttpMethod;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", "*");

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        String token = request.getHeader("tokenMiniAPP");

        if(token == null || token == "") {
            response.sendError(1001);
            return false;
        } else {
            JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
            DecodedJWT verify = build.verify(token);

            Claim a = verify.getClaim("openId");
            Claim b = verify.getClaim("userId");
            Claim c = verify.getClaim("shopId");
            if(a != null || b != null) {
                return true;
            }
            else {
                response.sendError(1001);
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        response.setHeader("Access-Control-Allow-Headers", "*");
    }
}
